<?php

class __admin_system_types extends Module {
	
	public function __construct () {
		parent::__construct('system');
	}
	
	public function types () {
		$response = $this->getTypes (true);
		$response->setTemplate ('system/types/list');
		
		if (getRequest ('created','bool')) {
			$response->addObject (new SystemMessage (lang('admin_type_created','system')));
		}
		if (getRequest ('saved','bool')) {
			$response->addObject (new SystemMessage (lang('admin_type_saved','system')));
		}
		if (getRequest ('deleted','bool')) {
			$response->addObject (new SystemMessage (lang('admin_type_deleted','system')));
		}
		if (getRequest ('imported','bool')) {
			$response->addObject (new SystemMessage (lang('admin_types_imported','system')));
		}
		
		return $response;
	}
	
	public function add_type () {
		return $this->formType ();
	}
	
	public function edit_type () {
		return $this->formType (getRequest ('param0','int'));
	}
	
	public function delete_type() {
		$typesController = TypesController::getInstance();
		$objectsController = ObjectsController::getInstance();
		
		$this->expectSecureGET();
		
		$typeId = getRequest('param0','int');
		
		if (!$oType = $typesController->getTypeById($typeId)) {
			throw new NotFound;
		}
		
		$sel = new Selection;
		$sel->addType($oType);
		
		$res = $sel->getList();
		
		foreach ($res as $row) {
			$objectsController->getObject($oType, $row[0])->delete();
		}
		
		$typesController->deletType($oType);
		
		redirect(HTTP_HOST . '/admin/system/types?deleted');
	}
	
	public function export_types() {
		$typesController = TypesController::getInstance();

		$aTypes = isset($_POST['types']) ? $_POST['types'] : array();
		
		if (!is_array($aTypes)) {
			$aTypes = (array) $aTypes;
		}
		
		$converter = new TypesExporter();
		
		foreach ($aTypes as $typeId) {
			$converter->addType($typesController->getTypeById($typeId));
		}
		
		header('Content-Disposition: attachment; filename="datatypes.xml"');
		$this->flush($converter->getXMLData()->saveXML(), 'text/xml');
	}
	
	public function ajax_import_types() {
		if (!isset($_FILES['file']) || $_FILES['file']['name'] == '') {
			$content = '<script type="text/javascript">parent.datatypesImportError("' . lang('error_admin_import_no_file','system') . '");</script>';
			$this->flush($content);
		}
		
		FilesController::uploadFile($_FILES['file'], ENGINE_ROOT . '/temp/datatypes.xml', true);
		
		$import = new TypesImporter(ENGINE_ROOT . '/temp/datatypes.xml');
		
		$aErrors = $import->validate();
		
		if (count($aErrors)) {
			$content = '<script type="text/javascript">parent.datatypesImportError("<ul><li>' . implode('</li><li>', $aErrors) . '</li></ul>");</script>';
			$this->flush($content);
		}
		
		$import->import();
		
		$content = '<script type="text/javascript">parent.location.href = parent.location.href+"?imported";</script>';
		$this->flush($content);
	}
	
	public function getTypes ($orderName = false) {
		$oType = TypesController::getInstance()->getTypeByName ('explay_type');
		
		$sel = new Selection;
		$sel->addType ($oType);
		$sel->setOrder ($orderName ? 'name' : 'title');
		
		$aObjects = ObjectsController::getInstance()->getObjectsList ($sel->getList ());
		
		$response = new ModuleResponse;
		
		foreach ($aObjects as $object) {
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	public function getTypeFields ($typeId) {
		$oTypeField = TypesController::getInstance()->getTypeByName ('explay_field');
		
		$sel = new Selection;
		$sel->addType ($oTypeField);
		$sel->addFilter ('type_id', $typeId);
		$sel->setOrder ('position');
		
		$aObjects = ObjectsController::getInstance()->getObjectsList ($sel->getList ());
		
		$response = new ModuleResponse;
		$response->setAttribute ('type-id', $typeId);
		
		foreach ($aObjects as $object) {
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	public function getTypeFieldsByOne ($fieldId) {
		if (!$oField = FieldsController::getInstance()->getField ($fieldId)) {
			return new ModuleResponse;
		}
		
		return $this->getTypeFields ($oField->getTypeId ());
	}
	
	public function ajax_get_type_fields () {
		$oTypeField = TypesController::getInstance()->getTypeByName ('explay_field');
		
		$sel = new Selection;
		$sel->addType ($oTypeField);
		$sel->addFilter ('type_id', getRequest ('param0','int'));
		$sel->setOrder ('position');
		
		$aObjects = ObjectsController::getInstance()->getObjectsList ($sel->getList ());
		
		$response = array ();
		
		foreach ($aObjects as $object) {
			$response[]['field'] = array (
				'id' => $object->getId (),
				'title' => $object->getValue ('title')
			);
		}
		
		$this->flush ((string) new Array2XML ('fields', $response), 'text/xml');
	}
	
	private function formType ($id = 'new') {
		$oType = TypesController::getInstance()->getTypeByName ('explay_type');
		
		$form = new Form ($oType, $id);
		$form->buildFromType ();
		
		$aValues = array ();
		$aErrors = array ();
		
		if ($id != 'new') {
			if (!$object = ObjectsController::getInstance()->getObject ($oType, $id)) {
				throw new NotFound;
			}
			
			$aValues = $object->getValues ();
		}
		
		if ((getRequest ('param1') == 'save' && $id != 'new') || (getRequest ('param0') == 'save' && $id == 'new')) {
			$aValues = $this->getRequestData ($id, $oType);
			
			if ($id == 'new') {
				$object = new Object ($oType);
				$object->setValues ($aValues);
				$object->setValue ('parend_id', 0);
				$object->setValue ('locked', 0);
				
				$aErrors = $this->getTypeValidate ($object, $id);
				
				if (!count ($aErrors)) {
					TypesController::getInstance()->createNewType ($object);
					$object->createNew ();
					
					redirect (HTTP_HOST . '/admin/system/types?created');
				}
			} else {
				$oldTableName = $object->getValue ('table_name');
				$object->setValues ($aValues);
				
				$aErrors = $this->getTypeValidate ($object, $id);
				
				if (!count ($aErrors)) {
					$tableName = $object->getValue ('table_name');
					
					if ($oldTableName != $tableName) {
						TypesController::getInstance()->renameTypeTable ($oldTableName, $tableName);
					}
					$object->save ();
					
					redirect (HTTP_HOST . '/admin/system/types?saved');
				}
			}
		}
		
		$form->setErrors ($aErrors);
		$form->setValues ($aValues);
		
		$response = new ModuleResponse;
		$response->setTemplate ('system/types/form');
		$response->addObject ($form);
		
		return $response;
	}
	
	private function getTypeValidate (Object $object, $id) {
		$aErrors = array ();
		
		if ($object->getValue ('name') == '') {
			$aErrors['name'] = lang('error_admin_type_empty_name','system');
		}
		
		if (!isset ($aErrors['name'])) {
			$sel = new Selection;
			$sel->addType ($object->getType ());
			$sel->addFilter ('name', $object->getValue ('name'));
			if ($id != 'new') {
				$sel->addFilter ('id', $id, '!=');
			}
			
			if ($sel->getTotalCount () != 0) {
				$aErrors['name'] = lang('error_admin_type_name_already_exists','system');
			}
		}
		
		if (!isset ($aErrors['name']) && !preg_match("#^[a-zA-Z0-9_]+$#", $object->getValue ('name'))) {
			$aErrors['name'] = lang('error_admin_type_name_latin','system');
		}
		
		if ($object->getValue ('title') == '') {
			$aErrors['title'] = lang('error_admin_type_empty_title','system');
		}
		
		if ($object->getValue ('table_name') == '') {
			$aErrors['table_name'] = lang('error_admin_type_empty_table','system');
		}
		
		return $aErrors;
	}
	
}